function PlayerSignHelp(sender, arg){
	Player = sender.getPlayer();
	if(!playData[Player.name]) playData[Player.name] = {
		LastSignInTime: 0,
		history: []
	};
	if(new Date(playData[Player.name].LastSignInTime).getDate() != new Date().getDate()) {
		PlayerSignWin(sender, Player);
	} else {
		NowSign(sender, Player);
	}// 检测是否为次日
}
function NowSign(play){// 已签到界面
	d = new Date();
	if(!signData[d.getFullYear()]) signData[d.getFullYear()] = {};
	if(!signData[d.getFullYear()][d.getMonth()]) signData[d.getFullYear()][d.getMonth()] = {};
	dayData = signData[d.getFullYear()][d.getMonth()][d.getDate()];
	if(!dayData || dayData.length === 0) {
		signData[d.getFullYear()][d.getMonth()][d.getDate()] = [];
		win = window.getSimpleWindowBuilder(d.toLocaleDateString() + ' 签到记录', '无人签到'); //创建窗口
	} else {// 如果有人签到
		playSignNum = checkSignNum(playData[play.name].history);
		str = "上次签到时间："+timeData2YMD(playData[play.name].LastSignInTime)
			+"\n当周签到次数："+playSignNum.week
			+"\n当月签到次数："+playSignNum.month
			+"\n总签到次数："+playData[play.name].history.length
			+"\n\n";
		for (i = 0; i<dayData.length; i++){
			str += timeData2YMD(dayData[i].date).split(' ')[1]+" "+dayData[i].name+">> "+dayData[i].sign+"\n";
		}
		win = window.getSimpleWindowBuilder(d.toLocaleDateString() + ' 签到记录', str); //创建窗口
	}
	win.showToPlayer(play, ''); //发送窗口
}
function PlayerSignWin(play){// 未签到界面
	win = window.getCustomWindowBuilder('签到'); //创建窗口
	win.buildInput('个性签名', '随便说点什么...');
	reward = "";
	if(Config.main.day.switch) {
		if(Config.main.day.display.length > 0) reward += "# Day:\n"+Config.main.day.display.join('\n');
	}
	playSignNum = checkSignNum(playData[play.name].history);
	if(Config.main.week.switch && playSignNum.week+1 === 7) reward += "# Week:\n"+Config.main.week.display.join('\n');
	if(Config.main.month.switch && playSignNum.month+1 === playSignNum.maxDay) reward += "# Month:\n"+Config.main.month.display.join('\n');
	for (i in Config.main.assign) {
		aData = Config.main.assign[i];
		if(aData.switch && new Date(i).toLocaleDateString() === new Date().toLocaleDateString() && new Date(i).setHours(0) > new Date(playData[play.name].LastSignInTime).getDate()) {
			reward += "\n# "+i+":\n"+aData.display.join('\n');
		}
	}
	win.buildLabel('可获得奖励：\n' + reward);
	win.showToPlayer(play, 'SignWinCallback'); //发送窗口
}
function SignWinCallback(play){// 未签到窗口回调
	input = window.getEventCustomVar(play, 0, "input");
	d = new Date();
	name = play.getPlayer().name;
	playData[name].LastSignInTime = d;
	playData[name].history.push({time: d, sign: input});
	manager.writeFile("./plugins/BlocklyNukkit/PlayerSign/PlayData.json", JSON.stringify(playData));
	if(!signData[d.getFullYear()]) signData[d.getFullYear()] = {};
	if(!signData[d.getFullYear()][d.getMonth()]) signData[d.getFullYear()][d.getMonth()] = {};
	dayData = signData[d.getFullYear()][d.getMonth()][d.getDate()];
	if(dayData === undefined || dayData.length === 0) signData[d.getFullYear()][d.getMonth()][d.getDate()] = [];
	signData[d.getFullYear()][d.getMonth()][d.getDate()].push({name: name, date: d.getTime(), sign: input});
	manager.writeFile("./plugins/BlocklyNukkit/PlayerSign/SignData.json", JSON.stringify(signData));
	NowSign(play.getPlayer());
	playSignNum = checkSignNum(playData[name].history);
	
	if(Config.main.day.switch) execList(Config.main.day, play.getPlayer());
	if(Config.main.week.switch && playSignNum.week+1 === 7) execList(Config.main.week, play.getPlayer());
	if(Config.main.month.switch && playSignNum.month+1 === playSignNum.maxDay) execList(Config.main.month, play.getPlayer());
	for (i in Config.main.assign) {
		if(aData.switch && new Date(i).toLocaleDateString() === new Date().toLocaleDateString() && new Date(i).setHours(0) > new Date(playData[name].LastSignInTime).getDate()) execList(Config.main.assign[i], play.getPlayer());
	}
}
function timeData2YMD(data){
	time = new Date(data);
	return time.toLocaleDateString()+' '+(time.getHours() < 10 ? "0"+time.getHours() : time.getHours())+':'+(time.getMinutes() < 10 ? "0"+time.getMinutes() : time.getMinutes())+':'+(time.getSeconds() < 10 ? "0"+time.getSeconds() : time.getSeconds());
}
function checkSignNum(data, date){
	t = date||new Date();
	maxDay = new Date(t.getFullYear(), Math.floor(t.getMonth() + 1), 0);
	back = {week: 0, month: 0, maxDay: maxDay.getDate()};
	minWeekTime = Math.floor((t.setHours(0) - (t.getDay()-1 < 0 ? 6 : t.getDay()-1)*1000*60*60*24)/1000000)*1000000;
	maxWeekTime = Math.floor(t.setHours(0)/1000 + (t.getDay() > 0 ? 8 - t.getDay() : 0)*60*60*24 - t.getMinutes()*60 - t.getSeconds() - 1)*1000;
	minMonthTime = Math.floor(t.setDate(1)/1000 - (t.getHours()*60 + t.getMinutes())*60 - t.getSeconds())*1000;
	maxMonthTime = maxDay.setHours(23) + 60*60*1000 -1;

	//server.broadcastMessage([minWeekTime, maxWeekTime, minMonthTime, maxMonthTime].join('/'))
	for(i = 0; i < data.length; i++){
		tempTime = new Date(data[i].time).getTime();
		if(minWeekTime < tempTime&&tempTime < maxWeekTime) back.week++;
		if(minMonthTime < tempTime&&tempTime < maxMonthTime) back.month++;
	}
	return back;
}
function execList(obj, play){
	if(obj.switch) {
		for (i in obj.exec) {
			if(Math.random() <= i) {
				for (j = 0; j < obj.exec[i].length; j++) {
					server.dispatchCommand(server.getConsoleSender(), obj.exec[i][j].replace("%player%", play.name));
				}
			}
		}
	}
}
// 初始化
if(manager.readFile('./plugins/BlocklyNukkit/PlayerSign/Config.yml') === "FILE NOT FOUND") {
	manager.createConfig(manager.getFile("PlayerSign", "PlayData.json"), 2);
	manager.createConfig(manager.getFile("PlayerSign", "SignData.json"), 2);
	manager.createConfig(manager.getFile("PlayerSign", "Config.yml"), 2);
	manager.writeFile("./plugins/BlocklyNukkit/PlayerSign/Config.yml", manager.JSONtoYAML(JSON.stringify(
		{language:'chs', version:'2020-05-28', main:{
			day: {
				switch: true,
				exec: {
					'1' : ['sblock cmd tell %player% 签到成功', 'givemoney %player% 10']
				},
				display: ["+ 10金币"]
			},
			week: {
				switch: true,
				exec: {
					'0.5' : ['sblock cmd tell %player% 恭喜你获得签到奖励']
				},
				display: []
			},
			month: {
				switch: true,
				exec: {
					'0.4' : ['sblock cmd tell %player% 恭喜你获得签到奖励']
				},
				display: []
			},
			assign: {
				"2020-06-01": {
					switch: true,
					exec: {
						'1' : ['sblock cmd tell %player% 61快乐']
					},
					display: ['+ 感谢有你']
				}
			}
		}}
	)));
}
if(manager.readFile('./plugins/BlocklyNukkit/PlayerSign/lang/chs.yml') === "FILE NOT FOUND") {
	manager.createConfig(manager.getFile("PlayerSign/lang", "chs.yml"), 2);
	manager.writeFile("./plugins/BlocklyNukkit/PlayerSign/lang/chs.yml", manager.JSONtoYAML(JSON.stringify(
		{cmd:{
			sign: '打开签到界面'
		},
		tips:{
			signSuccess: '签到 >>签到成功'
		}}
	)));
}
var playData = JSON.parse(manager.readFile("./plugins/BlocklyNukkit/PlayerSign/PlayData.json")),
signData = JSON.parse(manager.readFile("./plugins/BlocklyNukkit/PlayerSign/SignData.json")),
Config = JSON.parse(manager.YAMLtoJSON(manager.readFile("./plugins/BlocklyNukkit/PlayerSign/Config.yml"))),
lang = JSON.parse(manager.YAMLtoJSON(manager.readFile("./plugins/BlocklyNukkit/PlayerSign/lang/"+Config.language+".yml"))),
CommandList = [
	['sign', lang.cmd.sign]
];
for (i = 0;i<CommandList.length; i++){
	manager.createCommand(CommandList[i][0], CommandList[i][1], 'PlayerSignHelp');
}